package com.hh.jeecg;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread{
	private Socket socket;
	private InputStream in;
	private PrintStream out;
	private final static String WEB_ROOT="D:\\hh";
	public Processor(Socket socket){
		this.socket=socket;
		try {
			in=socket.getInputStream();
			out=new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void run(){
		String fileName=parse(in);
		sendFile(fileName);
	}
	//获取资源
	public String parse(InputStream in){
		BufferedReader br=new BufferedReader(new InputStreamReader(in));
		String filename="";
		try {
			String httpMessage=br.readLine();
			//浏览器发送的头信息
			String[] content=httpMessage.split(" ");
			System.out.println(content.toString());
			if(content.length!=3){
				sendErrorMessage(400, "client query error");
				return null;
			}
			filename=content[1];
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return filename;
	}
	//给浏览器发送错误信息
	public void sendErrorMessage(int errorCode,String errorMessage){
		out.println("HTTP/1.0" + errorCode+""+errorMessage);
		out.println("content-type:text/html");
		out.println();
		out.println("<html>");
		out.println("<title>Error Message");
		out.println("</title>");
		out.println("<body>");
		out.println("<h2>ErrorCode:"+errorCode+",Message Name"+errorMessage+"</h2>");
		out.println("</body>");
		out.println("</html>");
		out.close();
		try {
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	//给浏览器发送文件
	public void sendFile(String fileName){
		//判断方法是否存在
		File file=new File(Processor.WEB_ROOT+"//"+fileName);
		if(file.exists()){
			sendErrorMessage(404, "File Not Found");
			return ;
		}
		try {
			InputStream in=new FileInputStream(file);
			byte content[] =new byte[(int)file.length()];
			in.read(content);
			out.println("Http/1.0 200 queryfile");
			out.println("content-length:"+content.length);
			out.println();
			out.write(content);
			out.close();
			in.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
